<template>
    <div>
        <form class="sign-up">
            <div class="nicknameBox">
                <span><i class="fa fa-user"></i></span>
                <input type="text" class="nickname" placeholder="你的昵称" v-model="nickname.value"
                       @blur="asyncCheck('nickname','/api/register/checkNickname','昵称已存在!')">
                <transition name="form-tooltip">
                    <!--注意:不能使用v-if,因为v-if不会初始化组件,那么nickname.flag的值将永远不变,组件永久失效-->
                    <form-tooltip v-show="nickname.flag" :rules="nickname" ref="nickname"></form-tooltip>
                </transition>
            </div>
            <div class="telephoneBox">
                <span class="icon_phone"><i class="fa fa-mobile"></i></span>
                <input type="text" placeholder="手机号" v-model="telephone.value"
                       @blur="asyncCheck('telephone','/api/register/checkTelephone','手机号已注册!')">
                <transition name="form-tooltip">
                    <form-tooltip v-show="telephone.flag" :rules="telephone" ref="telephone"></form-tooltip>
                </transition>
            </div>
            <!--重新发送(xxs)-->
            <div v-if="!telephone.flag && telephone.checked" class="verificationCodeBox">
                <span><i class="fa fa-shield"></i></span>
                <input type="text" placeholder="手机验证码" v-model="verificationCode.value" @blur="checkVerCode">
                <button type="button" class="code" @click="send($event)">发送验证码</button>
                <transition name="form-tooltip">
                    <form-tooltip v-show="verificationCode.flag" :rules="verificationCode" ref="verificationCode"></form-tooltip>
                </transition>
            </div>
            <!--<i class="fa fa-expeditedssl" aria-hidden="true"></i>-->
            <div class="passwordBox">
                <span><i class="fa fa-lock"></i></span>
                <input type="password" class="password" placeholder="密码" v-model="password.value">
                <span class="icon-eye" @click="peep"><i class="fa fa-eye"></i></span>
                <transition name="form-tooltip">
                    <form-tooltip v-show="password.flag" :rules="password" ref="password"></form-tooltip>
                </transition>
            </div>
            <button type="button" @click.enter="commit" ref="btn">注册</button>
        </form>
    </div>
</template>

<script>
    import formTooltip from '@/components/tool/form-tooltip'
    import { Toast } from "mint-ui";
    import { Indicator } from 'mint-ui';
    export default {
        mounted(){
        },
        data(){
            return {
                nickname : {
                    value: '',
                    pattern : /^[\u4E00-\u9FA5a-zA-Z0-9_]{2,6}$/,
                    message : {
                        blank : '昵称不能为空!',
                        illegal : '昵称格式不正确,需要是2-6个字符,只能包含汉字,英文,数字和下划线,不能含有空格和其他特殊符号!'
                    },
                    flag : false,   //校验是否通过
                    target : 'nicknameBox',
                    checked : false, //是否已经校验过
                    asyncCheck : false,
                    asyncResult : false,
                    blurVal : ''
                },
                telephone : {
                    value: '',
                    pattern : /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
                    message : {
                        blank : '手机号不能为空!',
                        illegal : '手机号格式不正确!'
                    },
                    flag : false,
                    target : 'telephoneBox',    //在form-tooltip中用到
                    checked : false,
                    asyncCheck : false,
                    asyncResult : false,
                    blurVal : ''
                },
                password : {
                    value: '',
                    //必须包含字母和数字
                    pattern : /^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{6,12}$/,
                    message : {
                        blank : '密码不能为空!',
                        illegal : '密码格式不正确,需要是6-12个字符,必须包含英文和数字,不能含有空格和其他特殊符号!'
                    },
                    flag : false,
                    target : 'passwordBox',
                    checked : false
                },
                verificationCode : {
                    value : '',
                    message : {
                        blank : '验证码不能为空!'
                    },
                    flag : false,
                    target : 'verificationCodeBox',
                    checked : false,
                    asyncCheck : false,
                    asyncResult : false,
                    blurVal : ''    //记录失去焦点时的值
                }
            }
        },
        methods : {
            async commit(){
                var list = ['nickname','telephone','password','verificationCode']
                for(var i = 0; i < list.length; ++i){
                     if(!this[list[i]].checked){
                         this[list[i]].flag = true
                         this.$refs[list[i]].message = this[list[i]].message.blank
                         return
                     }
                     if(this[list[i]].flag) return
                 }
                //说明基本校验都通过
                for(i = 0; i < list.length; ++i){
                    while(this[list[i]].asyncCheck){
                        await new Promise((resolve,reject) => {
                            setTimeout(() => {
                                resolve()
                            },100)
                        })
                        console.log(1)
                    }
                }
                for(i = 0; i < list.length; ++i){
                    if(this[list[i]].asyncResult !== undefined && this[list[i]].asyncResult === false) return
                }
//                this.$store.commit('setLoading',true)
                Indicator.open({
                    text: '加载中...',
                    spinnerType: 'fading-circle'
                });
                //发送ajax请求提交表单数据
                this.$http.post('/api/register/add',{
                    params : {
                        nickname : this.nickname.value,
                        telephone : this.telephone.value,
                        password : this.password.value
                    }
                }).then(function(req){
//                    this.$store.commit('setLoading',false)
                    Indicator.close();
                    var result = req.data
                    if(result.status === 0){
                        this.$refs.btn.disabled = true
                        Toast({
                            message: '注册成功!',
                            iconClass: 'fa fa-check',
                            duration : 3000 //默认值
                        });
                        var timer = setTimeout(() => {
                            clearTimeout(timer)
                            this.reload()
                        },3000)
                    }
                    if(result.status === -1)
                        return Toast({
                            message: '出错啦!',
                            iconClass: 'fa fa-close'
                        });
                    if(result.status === 1)
                        return Toast({
                            message: '非法操作!',
                            iconClass: 'fa fa-close'
                        });
                },function(err){
//                    this.$store.commit('setLoading',false)
                    Indicator.close();
                })
            },
            peep(){
                var i = document.querySelector('.icon-eye i')
                i.classList.toggle('fa-eye-slash')
                i.classList.toggle('fa-eye')
                if(i.classList.contains('fa-eye'))
                    document.querySelector('.password').type = 'password'
                else
                    document.querySelector('.password').type = 'text'
            },
            send(event){
                //重置验证码文本框
                this.verificationCode.blurVal = ''
                this.verificationCode.value = ''
                //$event指向当前dom对象
                var button = event.target
                button.style.opacity = .7
                button.style.zIndex = -1
                var second = 6
                var timer = setInterval(function(){
                    second--
                    button.innerHTML = `重新发送(${second}s)`
                    if(second === 0){
                        button.innerHTML = '重新发送'
                        button.style.opacity = 1
                        button.style.zIndex = 1
//                        second = 10   为什么可以不需要重置?
                        clearInterval(timer)
                    }
                },1000)
                //调用api,发送短信
                //uri: /api/sendVerificationCode?telephone=xxxxxxx
                this.$http.get('/api/register/sendVerificationCode',{
                    params : {
                        telephone : this.telephone.value
                    }
                }).then(function(res){
                    var result = res.data
                    if(result.status !== 0)
                        return Toast({
                            message: '出错啦!',
                            iconClass: 'fa fa-close'
                        });
                    if(result.code !== 0)
                        return Toast({
                            message: '出错啦!',
                            iconClass: 'fa fa-close'
                        });
                },function(err){

                })
            },
            checkVerCode(){
                if(this.verificationCode.value === '' ||
                    this.verificationCode.blurVal === this.verificationCode.value) return
                this.verificationCode.blurVal = this.verificationCode.value
                this.verificationCode.asyncCheck = true
                //发送ajax请求校验
                this.$http.get('/api/register/checkVerCode',{
                    params : {
                        verCode : this.verificationCode.value,
                        telephone : this.telephone.value
                    }
                }).then(function(res){
                    this.verificationCode.asyncCheck = false
                    var result = res.data
                    if(result.status === 0) return this.verificationCode.asyncResult = true
                    this.verificationCode.asyncResult = false
                    this.verificationCode.flag = true
                    if(result.status === 1) return this.$refs.verificationCode.message = '验证码错误!'
                    this.$refs.verificationCode.message = '验证码无效或已过期，请重新发送验证码!'
                },function(err){
                    this.verificationCode.asyncCheck = false
                    this.verificationCode.asyncResult = false
                })
            },
            asyncCheck(target,uri,message){
                if(this[target].value === '' ||
                    this[target].blurVal === this[target].value || this[target].flag) return
                this[target].blurVal = this[target].value
                this[target].asyncCheck = true
                this.$http.get(uri,{
                    params : {
                        value : this[target].value
                    }
                }).then(function(res){
                    this[target].asyncCheck = false
                    var result = res.data
                    if(result.status === 0) return this[target].asyncResult = true
                    this[target].asyncResult = false
                    if(result.status === 1){
                        this[target].flag = true
                        return this.$refs[target].message = message
                    }
                    Toast({
                        message: '出错啦!',
                        iconClass: 'fa fa-close'
                    });
                },function(err){
                    this[target].asyncResult = this[target].asyncCheck = false
                })
            }
        },
        components : {
            formTooltip
        },
        watch : {
            'telephone.flag' : function(newVal, oldVal){
                if(oldVal === true && newVal === false) {
                    this.verificationCode.blurVal = ''
                    this.verificationCode.value = ''
                    this.verificationCode.checked = false
                    this.verificationCode.flag = false
                }
            }
        },
        inject : ['reload']
    }
</script>

<style scoped lang="less">
    .sign-up{
        width:100%;
        div{
            position: relative;
            span{
                position: absolute;
                left:14px;
                line-height:50px;
                font-size:20px;
                color:#969696;
                &.icon_phone{
                    font-size:28px;
                 }
                &.icon-eye{
                    top:0;
                    left:260px;
                 }
            }
        }
        input{
            &.nickname{
                 border-top: 1px solid #c8c8c8;
                 border-top-left-radius: 4px;
                 border-top-right-radius: 4px;
             }
            &.password{
                 border-bottom-left-radius: 4px;
                 border-bottom-right-radius: 4px;
             }
        }
        button{
            background: #3db922;
            &.code{
                 position: absolute;
                 top:7px;
                 right:10px;
                 width: 100px;
                 height: 36px;
                 line-height: 36px;
                 border-radius: 20px;
                 margin-top:0;
                 padding: 0;
                 font-size:14px;
             }
        }
    }
</style>

